import axios from 'axios'
import store from '@/store'
import { getToken } from '@/utils/auth'
import qs from 'qs'
import { Loading } from 'element-ui'

import { Message } from 'element-ui';
import {logout} from '@/api/logout'

var loadingInstace;

function closeLoading() {
  setTimeout(()=>{
    loadingInstace.close();
  }, 500);
}

// create an axios instance
const service = axios.create({
  baseURL: '', // api的base_url
  timeout: 5000, // request timeout
  url: '', // 默认给的url地址
  method: 'post'
});

// request interceptor
service.interceptors.request.use(config => {
  // 每次访问后端（操作），都需要更新超时时间
  let timelong = new Date().getTime();
  store.dispatch('setWebuiStarttime', timelong);

  if(config.isLoading){
    // 每次访问后端，都需要加载遮罩
    loadingInstace = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.4)',
      fullscreen: true
    });
  }

  config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  config.data = qs.stringify(config.data);
  // Do something before request is sent
  if (store.getters.token) {
    // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    config.headers['X-Token'] = getToken()
  }
  return config
}, error => {
  closeLoading();
  Promise.reject(error);
});

// respone interceptor
service.interceptors.response.use(
  response => {
    closeLoading();
    // console.log(response);
    const res = response.data;
    if (res.errorcode && res.errorcode !== "0") {

      // if(res.errorcode === "10003"){
      //   // 检测到未登录，直接返回登陆页
      //   Message.error(store.getters.language=='zh' ? '未登录':'Not logged');
      //   logout();
      //   return;
      // }

      //异常情况，直接返回错误码
      return Promise.reject(res.errorcode);
    } else {
      //正常情况，返回数据
      return res.data;
    }
  },
  error => {
    closeLoading();
    //异常情况，直接返回错误码
    //error是一个对象，数据从error.response中拿
    // console.log('error:'+error + '    error response'+ error.response);

    if(error.code === 'ECONNABORTED'){
      if(error.message.indexOf('timeout of 5000ms') > -1){
        return Promise.reject(504);
      }
      return Promise.reject('unknowError');
    }
    if(error.response.status === 401){
      return Promise.reject(401);
    }
    if(error.response.status === 403){
      return Promise.reject(403);
    }
    if(error.response.status === 404){
      return Promise.reject(404);
    }
    if(error.response.status === 500){
      return Promise.reject(500);
    }
    if(error.response.status === 504){
      return Promise.reject(504);
    }

    return Promise.reject('unknowError');
  });

export default service
